package web.servlet;

import com.alibaba.fastjson.JSON;
import com.pzhu.pojo.Brand;
import com.pzhu.service.BrandService;
import com.pzhu.service.impl.BrandServiceImpl;
import web.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

/**
 * @author Yancy xiao
 * @create 2023-04-03 11:28
 */
@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet {
    BrandService brandService = new BrandServiceImpl();

    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        BufferedReader reader = req.getReader();
        //1拿 到了post请求所传输的brand数据，json字符串
        String s = reader.readLine();
        //2将json字符串转换为对象
        Brand brand = JSON.parseObject(s, Brand.class);
        //3调用service中的add()添加数据到数据库表中
        brandService.add(brand);
        //通过resp带回成功标识
        resp.getWriter().write("success");
    }

    public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //查询所有数据
        List<Brand> brands = brandService.selectAll();
        //通过JSON.toJSONString把对象转换为字符串
        String s = JSON.toJSONString(brands);

        resp.setContentType("text/json;charset=utf-8");

        resp.getWriter().write(s);
    }

    public void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        BufferedReader reader = req.getReader();
        //1拿 到了post请求所传输的ids数据，json字符串
        String s = reader.readLine();
        //2将json字符串转换为数组
        int[] ids = JSON.parseObject(s, int[].class);

        brandService.deletByIds(ids);

        resp.getWriter().write("success");


    }

}
